package com.locus.locus.client.widgets;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Widget;
import com.locus.locus.client.dados.TweetWrapper;

public class WidgetTweet extends Composite implements ClickHandler {

	private static WidgetTweetUiBinder uiBinder = GWT
			.create(WidgetTweetUiBinder.class);

	interface WidgetTweetUiBinder extends UiBinder<Widget, WidgetTweet> {
	}

	@UiField
	Image imagem;
	@UiField
	HTML texto;
	
	private final String caminhoSite;

	public WidgetTweet(TweetWrapper tweet) {
		initWidget(uiBinder.createAndBindUi(this));

		final String html;
		final StringBuilder htmlFinal = new StringBuilder();
		String link;
		int posicaoFimLinkAnterior;
		int posicaoLink;
		int posicaoFimLink;

		this.caminhoSite = tweet.getCaminhoSite();

		this.imagem.setUrl(tweet.getCaminhoImagem());
		this.imagem.addClickHandler(this);
		this.imagem.setTitle(tweet.getNomeExibicao());
		this.imagem.setSize("48px", "48px");

		html = tweet.getTexto();
		posicaoLink = this.posicaoLink(html, 0);
		posicaoFimLinkAnterior = 0;

		/*while(posicaoLink != -1){
			posicaoFimLink = html.indexOf(' ', posicaoFimLinkAnterior);
			if(posicaoFimLink == -1){
				posicaoFimLink = html.length();
			}
			htmlFinal.append(html.substring(posicaoFimLinkAnterior, posicaoLink));
			htmlFinal.append("&nbsp;");
			link = html.substring(posicaoLink, posicaoFimLink);
			htmlFinal.append("<a href=\"" + link + "\">" + link + "</a>");
			
			posicaoFimLinkAnterior = posicaoFimLink;
			
			posicaoLink = this.posicaoLink(html, posicaoFimLinkAnterior);
		}*/
		htmlFinal.append(html.substring(posicaoFimLinkAnterior));

		this.texto.setText(htmlFinal.toString());
	}

	private int posicaoLink(String html, int from) {
		final int posicaoHttp = html.indexOf("http://", from);
		final int posicaoHttps = html.indexOf("https://", from);
		int posicao;
		
		posicao = -1;
		if (posicaoHttp != -1) {
			posicao = posicaoHttp;
		}
		if (posicaoHttps != -1 && (posicaoHttps < posicao || posicao == -1)) {
			posicao = posicaoHttps;
		}

		return posicao;
	}

	@Override
	public void onClick(ClickEvent event) {
		Window.Location.assign(this.caminhoSite);
	}

}
